import {
	host
} from '@/utils/config.js'
export const filterImg = (img) => {
	return img.indexOf('http') > -1 ? img : (this.host + img)
}
/**
 * 时间戳转日期格式
 * @param {Object} timeStamp
 */
export const timeStampTurnTime = function(timeStamp, type = "") {
	if (timeStamp != undefined && timeStamp != "" && timeStamp > 0) {
		var date = new Date();
		date.setTime(timeStamp * 1000);
		var y = date.getFullYear();
		var m = date.getMonth() + 1;
		m = m < 10 ? ('0' + m) : m;
		var d = date.getDate();
		d = d < 10 ? ('0' + d) : d;
		var h = date.getHours();
		h = h < 10 ? ('0' + h) : h;
		var minute = date.getMinutes();
		var second = date.getSeconds();
		minute = minute < 10 ? ('0' + minute) : minute;
		second = second < 10 ? ('0' + second) : second;
		if (type) {
			return y + '-' + m + '-' + d;
		} else {
			return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
		}

	} else {
		return "";
	}
}
/**
 * 随机字符串
 * @@param {Number} length长度
 */
export const randomString = function(length) {
	let chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
	var result = '';
	for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
	return result;
}

function getLocalFilePath(path) {
	if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf(
			'_downloads') === 0) {
		return path
	}
	if (path.indexOf('file://') === 0) {
		return path
	}
	if (path.indexOf('/storage/emulated/0/') === 0) {
		return path
	}
	if (path.indexOf('/') === 0) {
		var localFilePath = plus.io.convertAbsoluteFileSystem(path)
		if (localFilePath !== path) {
			return localFilePath
		} else {
			path = path.substr(1)
		}
	}
	return '_www/' + path
}

function dataUrlToBase64(str) {
	var array = str.split(',')
	return array[array.length - 1]
}

var index = 0

function getNewFileId() {
	return Date.now() + String(index++)
}

function biggerThan(v1, v2) {
	var v1Array = v1.split('.')
	var v2Array = v2.split('.')
	var update = false
	for (var index = 0; index < v2Array.length; index++) {
		var diff = v1Array[index] - v2Array[index]
		if (diff !== 0) {
			update = diff > 0
			break
		}
	}
	return update
}
//
export const pathToBase64 = function(path) {
	return new Promise(function(resolve, reject) {
		if (typeof window === 'object' && 'document' in window) {
			if (typeof FileReader === 'function') {
				var xhr = new XMLHttpRequest()
				xhr.open('GET', path, true)
				xhr.responseType = 'blob'
				xhr.onload = function() {
					if (this.status === 200) {
						let fileReader = new FileReader()
						fileReader.onload = function(e) {
							resolve(e.target.result)
						}
						fileReader.onerror = reject
						fileReader.readAsDataURL(this.response)
					}
				}
				xhr.onerror = reject
				xhr.send()
				return
			}
			var canvas = document.createElement('canvas')
			var c2x = canvas.getContext('2d')
			var img = new Image
			img.onload = function() {
				canvas.width = img.width
				canvas.height = img.height
				c2x.drawImage(img, 0, 0)
				resolve(canvas.toDataURL())
				canvas.height = canvas.width = 0
			}
			img.onerror = reject
			img.src = path
			return
		}
		if (typeof plus === 'object') {
			plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {
				entry.file(function(file) {
					var fileReader = new plus.io.FileReader()
					fileReader.onload = function(data) {
						resolve(data.target.result)
					}
					fileReader.onerror = function(error) {
						reject(error)
					}
					fileReader.readAsDataURL(file)
				}, function(error) {
					reject(error)
				})
			}, function(error) {
				reject(error)
			})
			return
		}
		if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
			wx.getFileSystemManager().readFile({
				filePath: path,
				encoding: 'base64',
				success: function(res) {
					resolve('data:image/png;base64,' + res.data)
				},
				fail: function(error) {
					reject(error)
				}
			})
			return
		}
		reject(new Error('not support'))
	})
}
// import router from '@/router/routers'

// 触发器总集合 扫码枪
const SCAN_LISTENER_MANAGER = []

function execFunc(listener, param) {
	listener.callback.call(listener.thisArg, param)
}

const scanListener = {

	/**
	 * 添加监听器
	 * @param {string} name
	 * @param {Function|*} listener
	 */
	on(name, listener) {
		if (!name || !isNaN(parseInt(name))) {
			throw TypeError('监听器名称只能为英文字母以及下划线！')
		}

		// 判断当前监听器是否存在，不存在则直接创建一个空数组
		if (SCAN_LISTENER_MANAGER[name] === undefined) {
			SCAN_LISTENER_MANAGER[name] = []
		}

		if (typeof listener !== 'object') {
			listener = {
				callback: listener
			}
		}

		if (typeof listener.callback !== 'function') {
			throw TypeError('监听器必须是一个function！')
		}

		SCAN_LISTENER_MANAGER[name].push(listener)
		return listener
	},

	/**
	 * 添加监听器 - 只执行一次
	 * @param {string} name
	 * @param {Function|*} listener
	 */
	once(name, listener) {
		if (typeof listener !== 'object') {
			listener = {
				callback: listener
			}
		}
		listener.once = true
		return this.on(name, listener)
	},

	/**
	 * 移除监听器
	 * @param {string} name
	 * @param {Function} listener
	 */
	off(name, listener) {
		if (!(typeof listener === 'function' || typeof listener === 'object')) return

		// 处理器
		const handler = (listeners, listener) => {
			if (typeof listener === 'object') {
				const index = listeners.indexOf(listener)
				if (index !== -1) listeners.splice(index, 1)
			} else if (typeof listener === 'function') {
				for (const i in listeners) {
					if (listeners[i].callback == listener) listeners.splice(i, 1)
				}
			}
		}

		if (!name || !isNaN(parseInt(name))) {
			// 所有监听器都移除这个回调函数
			SCAN_LISTENER_MANAGER.forEach(listeners => handler(listeners, listener))
		} else {
			handler(SCAN_LISTENER_MANAGER[name] || [], listener)
		}
	},

	/**
	 * 移除监听器, 移除指定事件名称下的所有回调方法
	 * @param {string} name
	 */
	offAll(name) {
		name &&
			SCAN_LISTENER_MANAGER[name] &&
			!SCAN_LISTENER_MANAGER[name].length &&
			(SCAN_LISTENER_MANAGER[name] = [])
	},

	/**
	 * 触发监听器
	 * @param {string} name
	 * @param {*} [param]
	 */
	emit(name, param) {
		if (!name || !isNaN(parseInt(name))) {
			throw TypeError('监听器名称只能为英文字母以及下划线！')
		}

		const listeners = SCAN_LISTENER_MANAGER[name] || []
		for (let i = 0; i < listeners.length; i++) {
			const listener = listeners[i]
			if (listener.once) {
				listeners.splice(i, 1)
				i--
			}
			execFunc(listener, param)
		}
	}

}


// 扫码监听器全局
export const keyinit = function(that) {
	/*
	 * 监听整个文档的keypress事件，识别键盘输入和扫码枪输入
	 * 扫码枪输入在回车符号后，向当前路由名称emit事件
	 * */
	console.log(that.isinput);
	let lastTimeStamp = null // 上一次记录的时间戳
	let codeString = '' // 记录内容
	let isScanInput = false // 是否处在扫码枪模式
	document.addEventListener('keypress', function(e) {
		console.log('监听按键');
		const timeStamp = e.timeStamp
		// 第一次记录字符
		if (lastTimeStamp == null) {
			lastTimeStamp = timeStamp
		}
		const diffTime = timeStamp - lastTimeStamp // 时间间隔
		const isNormalDiffTime = diffTime < 50 // 是否在 正常的扫码枪输入的时间间隔 范围之内
		// 是否 进入扫码模式 且在允许的时间间隔 范围之内
		const isScanDiffTime = isScanInput && !isNormalDiffTime && diffTime < 1000
		// 距上次记录间隔小于指定时间，或者 如果是扫码枪模式，允许一次较大时间
		if (isNormalDiffTime || isScanDiffTime) {
			if (isScanDiffTime) {
				isScanInput = false
			}
			// 如果是回车
			if (e.keyCode == '13') {
				// 有内容，则发送事件, 没有则跳出
				if (!codeString) return
				// 提取出记录到的内容
				const Result = codeString
				codeString = ''
				// 触发事件
				setTimeout(function() {
					// scanListener.emit(router.currentRoute.path, Result)
				}, 0)
			} else {
				// 小于100ms认为接下来是扫码枪模式
				if (isNormalDiffTime) isScanInput = true
				// 则堆加入内容
				codeString += String.fromCharCode(e.keyCode)
			}
		} else {
			isScanInput = false
			if (e.keyCode != '13') codeString = String.fromCharCode(e.keyCode)
		}
		// 记录当前输入的时间
		lastTimeStamp = timeStamp
	})
}